# from service.data import DataProcess
from pao_python.pao.data import process_db,dataframe_to_list,DataProcess
from service.common import getMonthFirstDayAndLastDay,get_cur_month
from service.enum import YearEnum
import datetime
import pandas as pd



#工业标识-统计分析服务接口实现
class IAnalysisStatistics(DataProcess):
    #标识总数统计
    def cal_line_data(self,handle_type):
        res = {}
        def process_func(db):
            nonlocal res
            cols = db['IDMIS_Handle']
            data_list = list(cols.find({'handle_type':handle_type}))
            if len(data_list) > 0:
                df_inner = pd.DataFrame(data_list)
                res = self.get_year_data(df_inner,'create_date')
            else:
                res = {'result':[],'model_total':0,'model_month_add':0}
        process_db(self.db_addr,self.db_port,self.db_name, process_func)
        return res
    #解析总数统计
    def cal_total_analysis_bar(self):
        res = {}
        def process_func(db):
            nonlocal res
            cols = db['IDMIS_Analysis_Record']
            data_list = list(cols.find({}))
            if len(data_list) > 0:
                df_inner = pd.DataFrame(data_list)
                res = self.get_year_data(df_inner,'date')
            else:
                res = {'result':[],'analysis_total':0,'analysis_add':0}
        process_db(self.db_addr,self.db_port,self.db_name, process_func)
        return res
    #解析总数排行统计
    def cal_analysStatistics(self,handle_type):
        res = []
        def process_func(db):
            nonlocal res
            cols = db['IDMIS_Analysis_Record']
            cols_handle = db['IDMIS_Handle']
            data_list = list(cols.find({'handle_type':handle_type})[:])
            if len(data_list) >0:
                pd_ft = pd.DataFrame(data_list)
                pd_data = pd_ft.groupby(by='handle_id').count().sort_values('date',ascending=False).head(10)
                handle_id_list = pd_data.index.tolist()
                count_list = pd_data['date'].tolist()
                handle_list = list(cols_handle.find({'id':{'$in':handle_id_list}}))[:]
                for i,x in enumerate(handle_id_list):
                    handle = pd_ft[pd_ft['handle_id'].isin([x])].drop(['_id'],axis=1).drop_duplicates(['handle_id'])
                    hanle_dict = dataframe_to_list(handle)[0]
                    for handle_mes in handle_list:
                        if x == handle_mes['id']:
                            res.append({
                                'id':hanle_dict['handle_id'],
                                'name':handle_mes['handle_name'],
                                'handle_name':hanle_dict['handle_code'],
                                'count':count_list[i],
                            })
            
        process_db(self.db_addr,self.db_port,self.db_name, process_func)
        return res
        
    def get_year_data(self,df_inner,field_name):
        res = {'result':[],'model_total':df_inner.shape[0],'model_month_add':0,'msg_code':True}
        for index,year in enumerate(YearEnum):
            month_date = getMonthFirstDayAndLastDay(month = index+1)
            month_data = df_inner.loc[(df_inner[field_name] >= month_date['first']) & (df_inner[field_name] <= month_date['last'])]
            # 1~12月份数据
            res['result'].append({'count':month_data.shape[0],'date':year.value})
            if get_cur_month() == index+1:
                res['model_month_add'] = month_data.shape[0]
        return res